//
//  comBlueboxmoonPhoneABLookup.m
//  ABLookup
//
//  Created by Daniel Hazelbaker on 4/4/09.
//  Copyright 2009 Blue Box Moon. All rights reserved.
//

#import "comBlueboxmoonPhoneABLookup.h"
#import "BMSnomPhone.h"
#import <AddressBook/AddressBook.h>
#import <AddressBook/ABAddressBookC.h>


@implementation comBlueboxmoonPhoneABLookup


//
// Set the default preferences.
//
+ (void)setDefaultPreferences
{
    BMPreferences *dict = [BMSnomPhone preferences];
    
    
    if ([dict valueForKey:kAddressBookEnableLookupKey] == nil)
	[dict setValue:[NSNumber numberWithBool:NO] forKey:kAddressBookEnableLookupKey];
}


//
// Lookup the person record for the given phone numbers. The array is all
// possible phone numbers to look for (i.e. area code prepended, etc.)
//
- (NSDictionary *)lookupPersonForPhoneNumbers:(NSArray *)possiblePhoneNumbers
{
    NSMutableDictionary	*newPerson = [NSMutableDictionary dictionary];
    ABAddressBook	*book;
    NSDictionary	*address;
    ABMultiValue	*phoneNumbers, *addresses;
    ABPerson		*person;
    NSString		*matchingLabel = nil, *phoneString;
    NSArray		*peopleFound, *people;
    int			i, x;

    
    //
    // Make sure we are enabled.
    //
    if ([[[BMSnomPhone preferences] valueForKey:kAddressBookEnableLookupKey] boolValue] == NO)
	return nil;

    //
    // Initialize the shared address book.
    //
    book = [ABAddressBook sharedAddressBook];

    //
    // Walk all the people in the address book looking for a match.
    //
    peopleFound = [NSMutableArray array];
    people = [book people];
    for (i = 0; i < [people count]; i++) {
	phoneNumbers = [[people objectAtIndex:i] valueForKey:kABPhoneProperty];
	for (x = 0; x < [phoneNumbers count]; x++) {
	    phoneString = [BMSnomPhone strippedPhoneNumber:[phoneNumbers valueAtIndex:x]];
        if ([phoneString characterAtIndex:0] == '1')
            phoneString = [phoneString substringFromIndex:1];

	    if ([possiblePhoneNumbers containsObject:phoneString] == YES) {
		[(NSMutableArray *)peopleFound addObject:[people objectAtIndex:i]];
		break;
	    }
	}
    }

    //
    // If nobody was found, return nil.
    //
    if ([peopleFound count] == 0)
	return nil;
    
    //
    // If one person was found, then all good.
    //
    if ([peopleFound count] == 1)
	person = [peopleFound objectAtIndex:0];
    else {
	//
	// More than one record, if any of them match the primary phone number
	// then use that one, otherwise abort.
	//
	for (i = 0; i < [peopleFound count]; i++) {
	    person = [peopleFound objectAtIndex:i];
	    
	    phoneNumbers = [person valueForKey:kABPhoneProperty];
	    for (x = 0; x < [phoneNumbers count]; x++) {
		phoneString = [BMSnomPhone strippedPhoneNumber:[phoneNumbers valueAtIndex:x]];

		if ([[possiblePhoneNumbers objectAtIndex:0] isEqual:phoneString] == YES)
		    break;
	    }
	}
	if (i == [peopleFound count])
	    return nil;
    }

    //
    // Find the matching label for the phone number we searched for.
    //
    phoneNumbers = [person valueForKey:kABPhoneProperty];
    for (i = 0; i < [phoneNumbers count]; i++) {
	if ([possiblePhoneNumbers containsObject:[BMSnomPhone strippedPhoneNumber:[phoneNumbers valueAtIndex:i]]]) {
	    matchingLabel = [phoneNumbers labelAtIndex:i];
	    break;
	}
    }

    //
    // Setup the new person record.
    //
    [newPerson setValue:[person valueForKey:kABTitleProperty] forKey:kPLTitleKey];
    [newPerson setValue:[person valueForKey:kABFirstNameProperty] forKey:kPLFirstNameKey];
    [newPerson setValue:[person valueForKey:kABLastNameProperty] forKey:kPLLastNameKey];
    [newPerson setValue:[phoneNumbers valueAtIndex:i] forKey:kPLPhoneNumberKey];
    [newPerson setValue:[(id)ABCopyLocalizedPropertyOrLabel((CFStringRef)matchingLabel) autorelease] forKey:kPLPhoneLabelKey];

    //
    // If we have an address for this phone number, use it.
    //
    addresses = [person valueForKey:kABAddressProperty];
    for (i = 0; i < [addresses count]; i++) {
	if ([matchingLabel isEqual:[addresses labelAtIndex:i]]) {
	    address = [addresses valueAtIndex:i];
	    [newPerson setValue:[address valueForKey:kABAddressStreetKey] forKey:kPLAddressStreetKey];
	    [newPerson setValue:[address valueForKey:kABAddressCityKey] forKey:kPLAddressCityKey];
	    [newPerson setValue:[address valueForKey:kABAddressStateKey] forKey:kPLAddressStateKey];
	    [newPerson setValue:[address valueForKey:kABAddressZIPKey] forKey:kPLAddressZIPKey];
	    [newPerson setValue:[address valueForKey:kABAddressCountryKey] forKey:kPLAddressCountryKey];
	}
    }

    //
    // Set the picture if we have one.
    //
    [newPerson setValue:[person imageData] forKey:kPLImageData];

    return newPerson;
}


@end
